<template>
    <div id="editor"></div>
</template>

<script>
import E from "wangeditor"
import axios from "axios"
export default {
    data: function() {
        return {
            msg: "",
            editor: null,
            aLiYunData: {},
        }
    },
    props: {
        value: {
            type: String,
            default: function() {
                return ""
            },
        },
    },
    name: "Ueditor",
    async mounted() {
        this.initEditor()
    },
    watch: {
        value(newValue) {
            if (this.editor) {
                this.editor.txt.html(newValue)
            }
        },
    },
    methods: {
        initEditor() {
            this.editor = new E("#editor")
            this.editor.config.onchange = newHtml => {
                this.msg = newHtml
            }
            this.editor.config.showLinkImg = false
            this.editor.config.excludeMenus = ["emoticon", "video", "code"]
            this.editor.config.customUploadImg = async (resultFiles, insertImgFn) => {
                // resultFiles 是 input 中选中的文件列表
                // insertImgFn 是获取图片 url 后，插入到编辑器的方法
                // let result = await axios.post("/aliyun/token")
                // aLiYunData.append("OSSAccessKeyId", result.data["AccessKeyId"])
                // aLiYunData.append("policy", result.data["Base64Policy"])
                // aLiYunData.append("Signature", result.data["Signature"])
                // aLiYunData.append("root", result.data["Root"])
                // aLiYunData.append("x-oss-security-token", result.data["SecurityToken"])
                // aLiYunData.append("key", result.data["Root"] + resultFiles[0].name)

                // nginx options跨域有问题 未解决  后改为通过后台接口进行了转接
                // await axios.post("/aliyun/imgList", aLiYunData, { headers: { "Content-Type": "application/x-www-form-urlencoded" } })

                let aLiYunData = new FormData()
                aLiYunData.append("file", resultFiles[0])
                let result = await this.axios.imgUpload(aLiYunData, { headers: { "Content-Type": "application/x-www-form-urlencoded" } })
                if (result.success) {
                    // 上传图片，返回结果，将图片插入到编辑器中
                    insertImgFn(result.instance)
                } else {
                    this.$message.error(result.errorMsg)
                }
            }
            this.editor.create()
        },
        getContent() {
            return this.editor.txt.html()
        },
    },
    beforeDestroy() {
        // 调用销毁 API 对当前编辑器实例进行销毁
        this.editor.destroy()
        this.editor = null
    },
}
</script>

<style lang="scss" scoped>
.ueditor-line-height {
    line-height: normal;
}
</style>
